<template>
  <!-- 智能保养 -->
  <view class="container" v-if="!loading">
    <view v-if="carList.length > 0">
      <view class="my-cars">
        <view class="flex flex-jc-sb">
          <view class="look pz"></view>
          <view class="look">
            <text @click="edit" :class="editname === '完成' ? 'editcss' :'editdelete'">{{editname}}</text>
            <text>|</text>
            <text @click="addConf">添加</text>
          </view>
        </view>
        <esc-swiper
          v-if="carList.length > 1"
          mode="3d"
          :autoplay="false"
          :scale="1.2"
          :circular="circular"
          :current.sync="current"
          :size="normalList.length"
          :plus="plus"
          :width="750"
          :height="420"
          :itemWidth="600"
          :itemHeight="340"
          :space="0"
        >
          <esc-swiper-item v-for="(item, idx) in normalList" :index="idx" :key="idx">
            <view class="item">
              <image :src="item.car_Tyoe_img" class="slide-image" :mode="item.heightFix ? 'heightFix' : 'aspectFit'"></image>
              <view class="icon-del" v-if="editname === '完成'" @click="onClickDelCar(item)">
                <i-icon icon="iconchacha" color="#FBD220" size="38rpx"></i-icon>
              </view>
              <view class="title">
                <text class="subtitle">{{item.brand_Name}} {{item.car_Type_Name}}</text>
                <!-- <text class="default" v-if="idx === 2">默认</text> -->
              </view>
              <view class="model">
                <text>{{item.car_Name}}</text>
              </view>
            </view>
          </esc-swiper-item>
        </esc-swiper>
        <view v-else style="width: 750rpx; height: 420rpx;" class="flex flex-ai-c">
          <view class="item" style="width: 600rpx;height: 340rpx;margin: 0 auto; transform: scale(1.2);">
            <image :src="carList[0].car_Tyoe_img" class="slide-image" :mode="carList[0].heightFix ? 'heightFix' : 'aspectFit'"></image>
            <view class="icon-del" v-if="editname === '完成'" @click="onClickDelCar(carList[0])">
              <i-icon icon="iconchacha" color="#FBD220" size="38rpx"></i-icon>
            </view>
            <view class="title">
              <text class="subtitle">{{carList[0].brand_Name}} {{carList[0].car_Type_Name}}</text>
              <!-- <text class="default" v-if="idx === 2">默认</text> -->
            </view>
            <view class="model">
              <text>{{carList[0].car_Name}}</text>
            </view>
          </view>
        </view>
      </view>
      
      <!-- 表单信息 -->
      <view class="form-box">
        <view class="tips"><text>请输入“行驶里程”和“上路时间”，精准检测保养项目</text></view>
        <view class="input-box">
          <view class="cell">
            <text class="title">行驶里程</text>
            <view class="input">
              <u-input v-model="value" type="number" input-align="center" placeholder="请输入行驶里程" />
              <text class="unit">km</text>
            </view>
          </view>
          <view class="line"></view>
          <view class="cell">
            <text class="title">上路时间</text>
            <view class="input">
              <u-input v-model="value1" type="text" input-align="center" placeholder="请选择上路时间" disabled @click="onClicTime" />
            </view>
          </view>
        </view>
      </view>
    </view>
    
    
    <view v-else class="top flex flex-jc-c flex-dir-c default" style="height: 160rpx;position: relative;">
    	<image src="https://files.yzsheng.com/client/index/carMaintenance/tianjiaqiche.png" style="width: 199rpx;height: 91rpx;position: absolute;bottom: 33rpx;right: 40rpx;"></image>
    	<view style="color: #666666;">添加爱车，提供精准适配服务</view>
    	<view class="add" @click="addConf">添加爱车<u-icon name="arrow-right"></u-icon></view>
    </view>
    
    <view class="content">
      <view class="meter">
        <image class="img" :src="meter1" mode="" v-if="submitBtnStatus === 1"></image>
        <image class="img" :src="meter2" mode="" v-if="submitBtnStatus === 2"></image>
        <image class="img" :src="meter3" mode="" v-if="submitBtnStatus === 3"></image>
        <image class="img" :src="meter4" mode="" v-if="submitBtnStatus === 4"></image>
      </view>
      
      <view class="project">
        <view class="cell">
          <text class="title">养护项</text>
          <view class="num">
            <u-count-to :start-val="0" :end-val="num" :duration="2000"></u-count-to>
          </view>
        </view>
        <view class="cell">
          <text class="title">更换项</text>
          <view class="num">
            <u-count-to :start-val="0" :end-val="num1" :duration="2000"></u-count-to>
          </view>
        </view>
      </view>
      
      <view class="btn flex flex-ai-c flex-jc-c" @click="onDoMaintenance" v-if="submitBtnStatus > 3">
        <text class="text">{{this.num}}项需养护（{{time}}s）</text>
      </view>
      
      <view class="btn flex flex-ai-c flex-jc-c" v-else @click="onStart" :class="{disabled: btnDisabled}">
        <text class="text">{{submitBtnStatus === 1 ? '开始检测' : '检测中'}}</text>
      </view>
    </view>
    
    
    <u-picker mode="time" :params="params" v-model="show" @confirm="confirm" :end-year="maxTime"></u-picker>
    
  </view>
</template>

<script>
import { getSwiperList } from '@/components/sn-swiper/esc-swiper/helper.js'
const dayjs = require('@/utils/dayjs.js')
export default {
  data() {
    return {
      editname: '删除',
      plus: 2,
      circular: true,
      current: 0,
      carList: [],
      value: '',
      value1: '',
      params: {
        year: true,
        month: true,
        day: true,
        hour: false,
        minute: false,
        second: false
      },
      show: false,
      num: 0, // 养护项
      num1: 0, // 更换项
      width: uni.upx2px(40) + '',
      loading: true,
      submitBtnStatus: 1, // 提交按钮状态 1：开始检测 2：检测中 3：结果
      result: null,
      timer: null ,// 定时器
      time: 5,
      btnFlag: false,
      meter1: '', // 仪表盘图片1,
      meter2: '', // 仪表盘图片2,
      meter3: '', // 仪表盘图片3,
      meter4: '', // 仪表盘图片4
      specifAll: {
        brandlist: null, //品牌
        Serieslist: null, //系列
        Displacement: null, //排量
        Modelyear: null, //年款
        Configulists: null, //车子
      },
      maxTime: dayjs().year()
    }
  },
  computed: {
    normalList() {
      return getSwiperList(this.carList, {
        circular: this.circular,
        plus: this.plus
      });
    },
    btnDisabled() {
      if(!this.value || !this.value1) {
        return true
      } else {
        return false
      }
    },
    userinfo() {
      return this.$store.state.userinfo
    }
  },
  onLoad() {
    uni.showLoading({
      title: '加载中'
    })
    this.getPreloadingImg()
    this.getMyLoveCar()
    
    // 选择品牌，系列，排量，年款，车子
    uni.$on('intelligence', data => {
      Object.assign(this.specifAll, data)
      if (data.licenseplate && data.pageFrom === 'intelligence') {
        this.addCar(this.specifAll)
      }
    })
  },
  methods: {
    async getUserInfo(callback) {
      if(this.userinfo) {
        callback && callback(true)
      } else {
        try{
          let res = await this.$api.user.GetUserInfomation()
          if(res.code === 200) {
            this.$store.commit('userinfo', res.data)
            callback && callback(true)
          } else {
            callback && callback(false)
          }
        }catch(e){
          callback && callback(false)
        }
      }
    },
    // 获取我的爱车
    getMyLoveCar() {
      this.getUserInfo(async data => {
        if(data) {
          try{
            let res = await this.$api.commodity.GetCarList({
              uid: this.userinfo.accountid
            })
            if(res.code === 200 && res.data.list.length > 0) {
              let list = res.data.list || []
              let imgArr = list.map(item => {
                return this.getImgInfo(item)
              })
              Promise.all(imgArr).then(data => {
                this.carList = data
              })
            } else if(res.code === 200 && res.data.list.length <= 0) {
              this.carList = []
            }
            this.loading = false
            uni.hideLoading()
          }catch(e){
            this.loading = false
            uni.hideLoading()
          }
        }
      })
    },
    //编辑
    async edit() {
      this.isIcon = !this.isIcon
      if (this.isIcon) {
        this.editname = '完成'
      } else {
        this.editname = '删除'
      }
    },
    //添加配置
    addConf() {
      uni.navigateTo({
        url: '/pages_common/addYourCar/addYourCar?type=120&pageFrom=intelligence'
      })
    },
    onClicTime(){
      this.show = true
    },
    confirm(data) {
      let {year, month, day} = data
      let time = `${year}-${month}-${day}`
      let current = dayjs().format('YYYY-MM-DD')
      if(dayjs(current).diff(time, 'day') >= 0) {
        this.value1 = time
      } else {
        uni.showToast({
          icon: 'none',
          title: '上路时间不能大于当前时间'
        })
        this.value1 = ''
      }
    },
    async onStart() {
      if(this.carList.length <= 0) {
        uni.showModal({
          content: '您还没有爱车，请先添加爱车后再试！',
          confirmText: '去添加',
          confirmColor: '#FBB000',
          success: res => {
            if(res.confirm) {
              uni.navigateTo({
                url: '/pages_common/addYourCar/addYourCar?type=120&pageFrom=intelligence'
              })
            }
          }
        })
        return false
      }
      if(this.btnDisabled || this.btnFlag) {
        uni.showToast({
          icon: 'none',
          title: '请输入行驶里程和上路时间'
        })
        return false
      }
      let date = new Date()
      this.num = 0
      this.num1 = 0
      this.time = 5
      
      let curingNum = 0 // 养护数量
      let replaceNum = 0 // 更换数量
      this.submitBtnStatus = 2
      try{
        this.btnFlag = true
        let res = await this.$api.maintenanceOrder.GetDoMaintenanceResponses({
          km: Number(this.value),
          months: dayjs().diff(dayjs(this.value1), 'month')
        })
        this.btnFlag = false
        if(res.code === 200) {
          res.data.map(item => {
            if(item.maintenance_Goods_Adapter === 3) {
              replaceNum += 1
            }
            if(item.maintenance_Goods_Adapter === 0) {
              curingNum += 1
            }
          })
          this.result = res.data
          let diff = new Date() - date
          setTimeout(() => {
            this.submitBtnStatus = 3
            setTimeout(() => {
              this.num = curingNum
              this.num1 = replaceNum
              this.submitBtnStatus = 4
              this.timer = setInterval(() => {
                this.time -= 1
                if(this.time <= 0) {
                  clearInterval(this.timer)
                  this.onDoMaintenance()
                }
              }, 1000)
            }, 1000)
          }, 2500 - diff)
        }
      }catch(e){
        this.btnFlag = false
      }
    },
    // 删除爱车
    onClickDelCar(data) {
      uni.showModal({
        content: '是否确认删除该爱车？',
        success: async (res) => {
          if(res.confirm){
            uni.showLoading({
              title: '加载中'
            })
            try{
              let res = await this.$api.common.DeleteCar({
                id: data.id
              })
              uni.hideLoading()
              uni.showToast({
                icon: 'none',
                title: res.msg
              })
              if(res.code === 200) {
                this.getMyLoveCar()
              }
            }catch(e){
              uni.hideLoading()
              uni.showToast({
                icon: 'none',
                title: '删除失败'
              })
            }
          }
        }
      })
    },
    // 去保养
    onDoMaintenance() {
      clearInterval(this.timer)
      let arr = this.result.map(item => {
        return item.maintenance_Type_Id
      })
      this.$store.commit('maintenanceCategory', {
        ids: arr,
        data: this.result
      })
      this.submitBtnStatus = 1
      uni.navigateTo({
        url: '/pages_commodity/doMaintenance/doMaintenance' + this.$u.queryParams({
          mileage: this.value,
          time: this.value1,
          from: 'intelligence',
          carId: this.carList[this.current].id || ''
        })
      })
    },
    // 预加载图片
    getPreloadingImg() {
      uni.getImageInfo({
        src: 'https://files.yzsheng.com/client/commodity/meter1.png',
        success: image => {
          this.meter1 = image.path
        }
      })
      uni.getImageInfo({
        src: 'https://files.yzsheng.com/client/commodity/meter2.gif',
        success: image => {
          this.meter2 = image.path
        }
      })
      uni.getImageInfo({
        src: 'https://files.yzsheng.com/client/commodity/meter3.gif',
        success: image => {
          this.meter3 = image.path
        }
      })
      uni.getImageInfo({
        src: 'https://files.yzsheng.com/client/commodity/meter4.png',
        success: image => {
          this.meter4 = image.path
        }
      })
    },
    // 添加爱车
    async addCar(data) {
      try{
        uni.showLoading({
          title: '加载中'
        })
        let res = await this.$api.common.AddCar({
          uid: this.userinfo.accountid,
          brand_Id: data.brandlist.bid,
          brand_Name: data.brandlist.brand,
          car_Type_Id: data.Serieslist.carTypeId,
          car_Type_Name: data.Serieslist.carTypeName,
          car_Id: data.Configulist.id,
          car_Name: data.Configulist.name,
          displacement: data.Displacement.pName,
          yeartype: data.Configulist.date,
          car_Num: data.licenseplate, //车牌号
        })
        uni.hideLoading()
        this.getMyLoveCar()
      }catch(e){
        uni.hideLoading()
      }
    },
    getImgInfo(item) {
      return new Promise((resolve, rejece) => {
        uni.getImageInfo({
          src: item.car_Tyoe_img,
          success(res) {
            if(res.width === 354 && res.height === 315) {
              item.heightFix = true
            }
            resolve(item)
          },
          fail() {
            resolve(item)
          }
        })
      })
    }
  },
  onUnload() {
    clearInterval(this.timer)
    uni.$off('intelligence')
  }
}
</script>

<style lang="scss">
page{
  background-color: #fff;
}
.container{
 background-color: #fff;
}
.my-cars{
  background: #FFFFFF;
  width: 750rpx;
  overflow: hidden;
  .look{
  	color: #666666;
    font-size: 26rpx;
  	margin: 30rpx 30rpx;
  	text{	
  		margin-left: 10rpx;
  	}
    .editcss{
      color: #FBB000;
    }
    .editdelete{
      color: #666666;
    }
  }
  .item {
  	display: flex;
  	flex-direction: column;
  	flex: 1;
  	align-items: center;
  	justify-content: center;
    position: relative;
    .icon-del{
      position: absolute;
      left: 80%;
      top: 0;
      &::after{
        content: '';
        display: block;
        width: 20rpx;
        height: 20rpx;
        position: absolute;
        left: 9rpx;
        top: 9rpx;
        background-color: #000;
        border-radius: 20rpx;
      }
      .iconfont{
        position: relative;
        z-index: 2;
      }
    }
    .slide-image{
      width: 460rpx;
      height: 360rpx;
    }
    .title{
      display: flex;
      align-items: center;
      font-size: 28rpx;
      color: #333;
      .default{
        background-color: #FED63F;
        height: 30rpx;
        line-height: 30rpx;
        border-radius: 5rpx;
        padding: 0 15rpx;
        font-size: 18rpx;
        color: #666;
        margin-left: 16rpx;
      }
    }
    .model{
      color: #999;
      font-size: 20rpx;
      margin-top: 10rpx;
    }
  }
}
.form-box{
  text-align: center;
  padding: 0 32rpx;
  margin-top: 10rpx;
  .tips{
    font-size: 24rpx;
    color: #FBB000;
  }
  .input-box{
    display: flex;
    align-items: center;
    margin-top: 30rpx;
    border-bottom: 2rpx solid #eee;
    .cell{
      flex: 1;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      padding: 0 40rpx;
      .title{
        font-size: 26rpx;
        color: #666;
      }
      .input{
        display: flex;
        align-items: center;
        justify-content: center;
      }
    }
    .line{
      width: 2rpx;
      height: 74rpx;
      background-color: #eee;
    }
  }
}
.content{
  margin-top: 78rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  .meter{
    width: 300rpx;
    height: 300rpx;
    // background-color: #EBEBEB;
    border-radius: 300rpx;
    .img{
      display: block;
      width: 100%;
      height: 100%;
    }
  }
  .project{
    width: 60%;
    display: flex;
    justify-content: space-around;
    margin-top: 46rpx;
    .cell{
      display: flex;
      align-items: center;
      flex-direction: column;
      .title{
        font-size: 32rpx;
        color: #666;
      }
      .num{
        font-weight: bold;
        color: #333;
        font-size: 72rpx;
        margin-top: 20rpx;
        .u-count-num{
          font-weight: bold !important;
          color: #333 !important;;
          font-size: 72rpx !important;;
        }
      }
    }
  }
  .btn{
    margin: 50rpx 0;
    width: 702rpx;
    height: 88rpx;
    background: linear-gradient(0deg, #FBD220, #FFE23E);
    border-radius: 44rpx;
    .text{
      font-size: 30rpx;
      color: #3d3d3d;
    }
    &.disabled{
      background: #eee;
      .text{
        color: #999;
      }
    }
  }
}
.top{
  padding: 35rpx 25rpx;
  margin: 25rpx 25rpx 0;
  background-color: #fff;
  box-shadow: 0 0 10rpx 0 rgba(0, 0, 0, 0.12);
  border-radius: 10rpx;
  .top-main{
    flex: 1;
  }
  
  .top-title{
    width: 400rpx;
    margin-left: 35rpx;
    font-size: 28rpx;
    font-weight: 500;
    color: #666666;
    
    .pz{
      display: -webkit-box;
      overflow: hidden;
      white-space: normal !important;
      text-overflow: ellipsis;
      word-wrap: break-word;
      -webkit-line-clamp: 1;
      -webkit-box-orient: vertical;
    }
    view:first-child{
      font-size: 34rpx;
      display: -webkit-box;
      overflow: hidden;
      white-space: normal !important;
      text-overflow: ellipsis;
      word-wrap: break-word;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
      font-weight: bold;
      color: #333333;
    }
  }
  
  
  .maintain{
    color: #3D3D3D;
    font-weight: 500;
    width: 163rpx;
    height: 54rpx;
    background: linear-gradient(0deg, #FBD220, #FFE23E);
    border-radius: 27rpx;
    text-align: center;
    line-height: 54rpx;
  }
  .top-logo{
    margin-left: 25rpx;
    width: 90rpx;
    height: 90rpx;
  }

  .default{
    padding: 0 42rpx;
    margin: 25rpx 25rpx 0;
    background-color: #fff;
    box-shadow: 0 0 10rpx 0 rgba(0, 0, 0, 0.12);
    border-radius: 10rpx;
  }
  .add{
    width: 200rpx;
    height: 60rpx;
    background: linear-gradient(0deg, #FBD220, #FFE23E);
    border-radius: 30px;
    font-size: 28rpx;
    font-weight: bold;
    color: #3D3D3D;
    text-align: center;
    line-height: 60rpx;
    margin-top: 20rpx;
  }
}
</style>
